<?php

namespace App\Http\Controllers\YApi;

//use Illuminate\Http\Request;
use Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use Session;
use Redirect;

use App\Models\UsersReg;

class RegwxusersController extends Controller
{

  	public function regwxusers()
  	{
		// 保存微信用户信息到主用户表（记录到网站会员主表users）

		$phonenumber = request::input('phonenumber');
		$openid = request::input('openid');
		$unionid = request::input('unionid');
		$wxusername = request::input('username');
		$touixiang = request::input('touixiang');
		$province = request::input('province');
		$city = request::input('city');
		$sex = request::input('sex');
		if($sex == 0)
		{
			$sex = 3; // 未知
		}
		if($sex == 1)
		{
			$sex = 1; // 男
		}
		if($sex == 2)
		{
			$sex = 2; // 女
		}

		$wxopenid = UsersReg::where('wxopenid', $openid)->first();
		if(empty($wxopenid))
		{
			// 如果openid没有注册过，微信用户第一次登录，保存注册信息
			$users = UsersReg::where('user_name', $wxusername)->first();
			if(empty($users))
			{
				// 没有重名的用户，添加
				$users = new UsersReg;
				$users->user_name = $wxusername;
				$users->mobile = $phonenumber;
				$users->sex = $sex;
				$users->wxopenid = $openid;
				$users->wxunionid = $unionid;
				$users->province = $province;
				$users->city = $city;
				$users->reg_time = time();
				$users->reg_laiyuan = 'w'; // 微信注册
				$users->save();
			}
			else {
				// 有重名的用户，用户名后跟_userid
				$users = new UsersReg;
				// $users->user_name = $wxusername;
				$users->mobile = $phonenumber;
				$users->sex = $sex;
				$users->wxopenid = $openid;
				$users->wxunionid = $unionid;
				$users->province = $province;
				$users->city = $city;
				$users->reg_time = time();
				$users->reg_laiyuan = 'w'; // 微信注册
				$users->save();

				$username = UsersReg::where('wxopenid', $openid)->first();
				$username->user_name = $wxusername . $users->uid;
				$username->save(); // 重名用户名后跟_userid
			}

			// 获得微信头像

			$url = $touixiang; // 微信头像地址
			$userid = $users->uid;		
			$path = 'usersface/' . $userid . '/'; // 头像保存路径
			$files_max = 'face_' . $userid . '_max'; // 大头像，文件名，不包含扩展名
			$files_min = 'face_' . $userid . '_min'; // 大头像，文件名，不包含扩展名

			if(!file_exists($path)){       //判断保存目录是否存在
	            mkdir($path,0777,true);    //建立保存目录
	        }

			$face_max = $this->download_remote_pic($url, $path, $files_max);  // 大头像
			$face_min = $this->download_remote_pic($url, $path, $files_min);  // 小头像
			
			// 保存头像路径到数据表 
			$face = UsersReg::where('wxopenid', $openid)->first();
			$face->avatar_file = $face_max;
			$face->avatar_file_min = $face_min;
			$face->save();

			return 2; // 微信用户保存成功
		}
		else {
			// 已经有openid了，微信用户已经注册过信息
			return 1; 
		}	

    }

    public function download_remote_pic($url, $path, $files)
    {
	    $header = [
	        'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',      
	        'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',      
	        'Accept-Encoding: gzip, deflate',
	    ]; 

	    $curl = curl_init();
	    curl_setopt($curl, CURLOPT_URL, $url);
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  
	    // curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
	    curl_setopt($curl, CURLOPT_ENCODING, 'gzip');  
	    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
	    $data = curl_exec($curl);
	    $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
	    curl_close($curl);  
	    if ($code == 200) {//把URL格式的图片转成base64_encode格式的！      
	       $imgBase64Code = "data:image/jpeg;base64," . base64_encode($data);  
	    }  
	    $img_content=$imgBase64Code;//图片内容  
	    //echo $img_content;exit;  
	    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result)) {   
	        $type = $result[2];//得到图片类型png?jpg?gif?   
	        // $new_file = "./".time().rand(1,10000).".{$type}"; 
	        $new_file = $path . $files . '.' . $type;   
	        if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img_content)))) {  
	            return $new_file; 
	        }
	    } 
	}
    
}